export default{
    namespaced: true,
    state: {
        carts:[]
    },
    mutations: {
        SET_CART(state,payload){
            // 如果数组中已经有对应数据则 count数量+1 没有就添加进去
            let target = state.carts.find(item=>item.id===payload.id)
            if(target){
                target.count++
            }else{
                let obj = {
                    id:payload.id,
                    title:payload.title,
                    price:payload.price,
                    count:1
                }
                state.carts.push(obj)
            }
        },
        DECREASE_CART(state,payload){
            let target = state.carts.find(item=>item.id===payload.id)
            if(target){
                target.count--
            }
            if(target.count===0){
                state.carts = state.carts.filter(item=>item.count!==0)
            }
        }
    },
    actions: {
        ADD_TO_CART(context,payload){
            console.log(context)
            context.commit('SET_CART',payload)  // 将结果通过context上的commit提交给mutations
            context.commit('product/DECREASE_INVENTORY',payload,{root:true})  // 将payload里面的id提交
        },
        REMOVE_CART(context,payload){
            context.commit('DECREASE_CART',payload)  // 数量 -1
            context.commit('product/DECREASE_PRODUCT',payload,{root:true}) // 数量 +1 product库存
        }
    },
    getters: {
        total(state){
            return(
                state.carts.reduce((total,item)=>{
                    return total += item.count*item.price
                },0)
            ).toFixed(2)
        }
    },

    modules: {},
}